const http = require('http');
const url = require('url');
const path = require('path');
const fs = require('fs');

let port = process.argv[2] || 3000;
let server = http
  .createServer(function (request, response) {
    let uri = url.parse(request.url).pathname;
    let filename = path.join(process.cwd(), 'dist', uri);

    let contentTypesByExtension = {
      '.html': 'text/html',
      '.css': 'text/css',
      '.js': 'text/javascript',
    };

    fs.exists(filename, function (exists) {
      if (!exists) {
        response.writeHead(404, { 'Content-Type': 'text/plain' });
        response.write('404 Not Found\n');
        response.end();
        return;
      }
      if (fs.statSync(filename).isDirectory()) filename += '/index.html';

      fs.readFile(filename, 'binary', function (err, file) {
        if (err) {
          response.writeHead(500, { 'Content-Type': 'text/plain' });
          response.write(err + '\n');
          response.end();
          return;
        }

        let headers = {};
        let contentType = contentTypesByExtension[path.extname(filename)];
        if (contentType) headers['Content-Type'] = contentType;
        response.writeHead(200, headers);
        response.write(file, 'binary');
        response.end();
      });
    });
  })
  .listen(parseInt(port, 10));

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  let bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  let addr = server.address();
  let bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

const startServer = () => {
  /**
   * Listen on provided port, on all network interfaces.
   */

  // server.listen(port);
  server.on('error', onError);
  server.on('listening', onListening);
};

module.exports.startServer = startServer;
